using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Work.API.Applications.Read.Commands;
using Work.API.Dtos.DrugManagement;
using Work.Domain.DrugManage;
using Work.ErrorCode;
using Work.Infrastructure.Interfaces;

namespace Work.API.Applications.Read.CommandHandlers
{
    /// <summary>
    /// 根据药品ID查询入库记录处理器
    /// 功能：根据药品ID查询该药品的所有入库记录，支持时间范围筛选
    /// </summary>
    public class GetDrugInboundRecordsByDrugIdQueryHandler : IRequestHandler<GetDrugInboundRecordsByDrugIdQuery, ApiResult<List<DrugInboundDto>>>
    {
        private readonly IBaseRepository<DrugInbound> _inboundRepo;
        private readonly IBaseRepository<Drug> _drugRepo;
        private readonly IMapper _mapper;

        public GetDrugInboundRecordsByDrugIdQueryHandler(
            IBaseRepository<DrugInbound> inboundRepo,
            IBaseRepository<Drug> drugRepo,
            IMapper mapper)
        {
            _inboundRepo = inboundRepo;
            _drugRepo = drugRepo;
            _mapper = mapper;
        }

        public async Task<ApiResult<List<DrugInboundDto>>> Handle(GetDrugInboundRecordsByDrugIdQuery request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<List<DrugInboundDto>>();

            try
            {
                // 1. 验证药品是否存在
                var drug = await _drugRepo.GetById(request.DrugId);
                if (drug == null || !drug.IsEnabled)
                {
                    result.Code = ApiEnum.失败;
                    result.Message = "药品不存在或已禁用";
                    result.Data = new List<DrugInboundDto>();
                    return result;
                }

                // 2. 构建查询条件：根据药品ID查询入库记录
                var query = _inboundRepo.GetAll()
                    .Where(di => di.DrugId == request.DrugId)
                    .Include(di => di.Drug) // 关联药品信息，用于填充DrugName
                    .AsNoTracking();

                // 3. 时间范围筛选（如果提供了开始日期）
                if (request.StartDate.HasValue)
                {
                    query = query.Where(di => di.InboundDate >= request.StartDate.Value);
                }

                // 4. 时间范围筛选（如果提供了结束日期）
                if (request.EndDate.HasValue)
                {
                    query = query.Where(di => di.InboundDate <= request.EndDate.Value);
                }

                // 5. 按入库日期倒序排列（最新的在前）
                var inbounds = await query
                    .OrderByDescending(di => di.InboundDate)
                    .ThenByDescending(di => di.CreateTime)
                    .ToListAsync(cancellationToken);

                // 6. 映射为DTO，并填充药品名称
                var dtoList = new List<DrugInboundDto>();
                foreach (var inbound in inbounds)
                {
                    var dto = _mapper.Map<DrugInboundDto>(inbound);
                    // 填充药品名称（如果关联的药品信息存在）
                    if (inbound.Drug != null)
                    {
                        dto.DrugName = inbound.Drug.DrugName;
                    }
                    dtoList.Add(dto);
                }

                result.Code = ApiEnum.成功;
                result.Message = $"查询成功，共找到 {dtoList.Count} 条入库记录";
                result.Data = dtoList;
            }
            catch (System.Exception ex)
            {
                result.Code = ApiEnum.失败;
                result.Message = $"查询入库记录失败：{ex.Message}";
                result.Data = new List<DrugInboundDto>();
            }

            return result;
        }
    }
}


